/**
 * @description 本地数据操作
 */

import { strer, loger, SqliteDataBase, DberDataBase, dater } from '@daelui/dogjs/dist/components.js'
import { isPlus } from '@/utils/common.js'
import uniFiler from '@/components/libs/uni-filer.js'
import tables from '@/static/database/table.json'

// 初始化本地数据库
let database = null
const options = {
	dbName: 'dpod',
	dbTables: tables
}
if (isPlus()) {
	database = new SqliteDataBase(options)
} else {
	database = new DberDataBase(options)
}

export {
	database
}

export default {
	// 初始化本地数据
	initLocalDatabase (view) {
    // 初始化本地数据表
    return this.initBaseDatabase().finally(() => {
      // 初始化更新数据表
      return this.initBaseDatabase()
    })
	},

	// 初始化表结构
	initBaseDatabase () {
		return new Promise((resolve, reject) => {
			 let defer = Promise.resolve(true)
			 tables.forEach(item => {
				 defer = defer.then(() => {
					 return database.initTable(item.name, item.fields)
				 })
			 })
			 defer.then(e => {
				 loger.log('initBaseDatabase success')
				 resolve(e)
			 }).catch(e => {
				 loger.error('initBaseDatabase error')
				 loger.error(e)
				 reject(e)
			 })
		})
	},

  // 初始化更新数据库
  initUpdateDatabase () {
    let defers = []
    /*20240417###############################*/
    let tableName = 'dpod_note'
    let sql = `PRAGMA table_info('${tableName}')`
    let defer = database.query(sql).then(res => {
      res = Array.isArray(res) ? res : []
      let images = res.find(item => item.name === 'images')
      if (!images) {
        return database.execute(`ALTER TABLE ${tableName} ADD COLUMN images TEXT`)
      }
    }).catch(e => {
      console.log(e)
    })
    defers.push(defer)
    /*20240417###############################*/
    return Promise.allSettled(defers)
  },

  // 执行更新数据库
  executeUpdateDatabase () {
    return Promise.resolve()
  },

  // 初始化数据库数据
  initDatabaseData (view, callback, check) {
    return Promise.resolve()
  },

  /*
	// 初始化基础数据表
	initBaseDatabase (callback) {
	  return new Promise((resolve, reject) => {
	    uniFiler.readFile('_www/static/database/table.sql').then(e => {
	      let sql = e.target.result
	      let sqls = sql.split(';')
	      database.execute(sqls).then(e => {
	        loger.log('initBaseSql success')
	        resolve()
	      }).catch(e => {
	        loger.error('initBaseSql error')
	        loger.error(e)
	        reject(e)
	      })
	    }).catch(e => {
	      loger.error('initBaseSql error')
	      loger.error(e)
	      reject(e)
	    })
	  })
	},
	
	// 初始化更新数据库
	initUpdateDatabase () {
	  return new Promise((resolve, reject) => {
	    let logTable = 'database_update_log'
	    let logSql = `
	      create table if not exists "database_update_log" (
	        "id" integer NOT NULL PRIMARY KEY,
	        "sign" integer(20) DEFAULT 0,
	        "description" TEXT(50),
	        "time" TEXT(50)
	      )
	    `
	    // 初始化日志表
	    database.execute(logSql).then(() => {
	      // 查询日志表数据
	      database.query("select * from database_update_log").then(list => {
	        let logs = Array.isArray(list) ? list : []
	        uniFiler.readFile('_www/static/sql/update.sql').then(e => {
	          let sql = e.target.result
	          let sqls = sql.split(';')
	          let temp = [], groups = []
	          // 对sql文件字符进行分组
	          sqls.forEach(node => {
	            if (/@update/.test(node)) {
	              temp = [node]
	              groups.push({
	                description: (/@update (.+)?/.exec(node) || [])[1] || '',
	                sqls: temp
	              })
	            } else {
	              temp.push(node)
	            }
	          })
	          // 执行
	          this.executeUpdateDatabase(groups, logs).then(() => {
	            resolve()
	          }).catch(e => {
	            reject(e)
	          })
	        }).catch(e => {
	          loger.error('get update sql error')
	          loger.error(e)
	          reject(e)
	        })
	      })
	    }).catch(e => {
	      loger.error('init update log sql error')
	      loger.error(e)
	      reject(e)
	    })
	  })
	},
	
	// 执行更新数据库
	executeUpdateDatabase (groups, logs) {
	  let logTable = 'database_update_log'
	  let defer = Promise.resolve(true)
	  groups.forEach((group, index) => {
	    let node = logs.find(item => String(item.sign) === String(index))
	    // 该分组已经执行过
	    if (node) {
	      return true
	    }
	    defer = defer.then((b) => {
	      // 已经选择失败
	      if (b === false) {
	        return false
	      }
	      // 执行update sql
	      return database.execute(group.sqls).then(e => {
	        // 记录修改日志
	        return database.table(logTable).insert({
	          id: strer.udigit(),
	          sign: index,
	          description: group.description,
	          time: dater.format(new Date())
	        })
	      }).catch(e => {
	        return false
	      })
	    })
	  })
	  return defer
	},
	
	// 初始化数据库数据
	initDatabaseData (view, callback, check) {
	  // 查询所有的配置表
	  return queryTables().then(res => {
	    let data = res.data
	    data = Array.isArray(data) ? data : []
	    let user = view.getCurrentUser() || {}
	    let defer = Promise.resolve(true)
	    data.forEach(item => {
	      defer = defer.then(() => {
					let b = true
					if (typeof check === 'function') {
						b = check(item)
					}
					if (b === false) {
						return true
					}
					// 回调
					if (typeof callback === 'function') {
						callback(item)
					}
	        return queryTableData({
	          url: item.url
	        }).then(res => {
	          let data = res.data
	          data = Array.isArray(data) ? data : []
	          item.data = data
	        }).then(() => {
						// 先删除旧数据
						return database.table(item.tableName).delete({ userId: user.userId }, { isRequireMatch: false }).then(() => {
							// 添加数据
							return database.table(item.tableName).insertAll(item.data || [])
						}).catch(e => loger.error(e))
					})
	      })
	    })
	    return defer
	  })
	}
  */
}
